const chokidar = require('chokidar');
const fs = require('fs');
const _ = require('lodash');
const exec = require("@appgeist/exec");

const NAT_LOG_FILE = 'nat.log';
const COMMIT_FILE = 'index.json';
let preUrl = ''
const tcpRegex = /tcp:\/\/[0-9a-zA-Z.]+:[\d]+/;
const errorRegex = /EROR/;
const psCheckRegx = /natapp -config=/;
const idGetRegx = /[\d]{3,}/g;

const watcher = chokidar.watch(NAT_LOG_FILE, {
  persistent: true
});

const resolveUrl = (data) => Promise.resolve(data.split('\n'))
  .then(dataArray => {
    const error = dataArray.filter(v => errorRegex.test(v));
    const success = dataArray.filter(v => tcpRegex.test(v));
    if (error.length > 0) {
      return Promise.reject(error)
    } else if (success.length > 0) {
      const successUrl = success.pop().split(' ').pop()
      console.log('======', dataArray, success, successUrl, '======')
      return Promise.resolve(successUrl)
    }
    return Promise.resolve('unchanged')
  });

const onChange = _.debounce(async (path, stats) => {
  if (path === NAT_LOG_FILE && stats.size > 0) {
    console.log(`${NAT_LOG_FILE} changed, size if ${stats.size}`);
    const data = fs.readFileSync(NAT_LOG_FILE, {encoding: 'UTF-8'});
    console.log('read data: ', data);
    let url = ''
    try {
      const tmpUrl = await resolveUrl(data);
      if (tmpUrl !== 'unchanged') {
        url = tmpUrl;
      }
    } catch (e) {
      console.log('natapp error:', e);
      const natProcessInfo = (await exec('ps -ef|grep natapp'))
        .split('\r\n')
        .filter(v => psCheckRegx.test(v))[0];
      if (natProcessInfo) {
        const pid = natProcessInfo.match(idGetRegx)[0]
        console.log(natProcessInfo, pid);
        if (pid) {
          console.log(`kill -9 ${pid} and restart natapp`)
          await exec(`kill -9 ${pid}`)
          await exec('nohup ./natapp -config=./config.ini > nat.log 2>&1 &')
        }
      }
      return;
    }
    // const url = data.split('\n').filter(v => tcpRegex.test(v)).pop().split(' ').pop();
    console.log('get url: ', url)
    if (!url || url === preUrl) {
      console.log('url not change');
      return
    }
    preUrl = url;
    fs.writeFileSync(NAT_LOG_FILE, '');
    fs.writeFileSync(COMMIT_FILE, JSON.stringify({ url }));
    try {
      console.log(`git add ${COMMIT_FILE}`);
      await exec(`git add ${COMMIT_FILE}`);
      console.log(`git commit -m "${url}"`);
      await exec(`git commit -m "${url}"`);
      console.log('git push');
      await exec('git push')
    } catch (e) {
      console.log(e)
    }
  }
}, 2000);

watcher
  .on('change', onChange);
console.log('start watch ...');

